"""
查询历史记录管理
"""
import json
from typing import List, Dict, Any
from datetime import datetime


class HistoryManager:
    """
    查询历史记录管理
    """
    def __init__(self, history_file: str = "query_history.json"):
        """
        初始化历史记录管理器
        
        Args:
            history_file: 历史记录文件路径
        """
        self.history_file = history_file
        self.history = self._load_history()

    def _load_history(self) -> List[Dict[str, Any]]:
        """
        加载历史记录
        """
        try:
            with open(self.history_file, "r", encoding="utf-8") as f:
                return json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            return []

    def _save_history(self) -> None:
        """
        保存历史记录
        """
        with open(self.history_file, "w", encoding="utf-8") as f:
            json.dump(self.history, f, ensure_ascii=False, indent=4)

    def add_query(self, query: str, result: Dict[str, Any]) -> None:
        """
        添加查询记录
        
        Args:
            query: SQL 查询语句
            result: 查询结果
        """
        self.history.append({
            "timestamp": datetime.now().isoformat(),
            "query": query,
            "result": result
        })
        self._save_history()

    def get_history(self) -> List[Dict[str, Any]]:
        """
        获取历史记录
        """
        return self.history